#include <basic/errcode.h>
#include <basic/http.h>

char *url_encode(char *url, char *url_enc)
{/*{{{*/
    if(!url_enc) return(NULL);
    CLR_BUF(url_enc);
    if(!url) return(NULL);

    int urllen=strlen(url);
    char *buf;
    ALLOC_MULTI_RETERR(buf, char, urllen*3+1, NULL);

    int x, y;
    for(x=0, y=0; urllen--; x++, y++)
    {
        if(url[x] == ' ')
        {   buf[y]='+';   }
        else if(url[x] == '-' || url[x] == '.' || url[x] == '_' ||
                ('0' <= url[x] && url[x] <= '9') ||
                ('A' <= url[x] && url[x] <= 'Z') ||
                ('a' <= url[x] && url[x] <= 'z'))
        {   buf[y]=url[x];   }
        else
        {
            buf[y]='%';
            ++y;
            expand_to_str((unsigned char *)url+x, 1, buf+y);
            ++y;
        }
    }
    buf[y]=ZERO;
    strcpy(url_enc, buf);

    free(buf);
    return(url_enc);
}/*}}}*/

char *url_decode(char *url_enc, char *url)
{/*{{{*/
    if(!url) return(NULL);
    CLR_BUF(url);
    if(!url_enc) return(NULL);

    int urlelen=strlen(url_enc);
    char *buf;
    ALLOC_MULTI_RETERR(buf, char, urlelen+1, NULL);

    int x, y;
    for(x=0, y=0; urlelen--; x++, y++)
    {
        if(url_enc[x] == '+')
        {   buf[y]=' ';   }
        else if(url_enc[x] == '%' && urlelen >= 2 &&
                isxdigit(url_enc[x+1]) && isxdigit(url_enc[x+2]))
        {
            collapse_from_str(url_enc+x+1, 2, (unsigned char *)buf+y);
            x+=2;
            urlelen-=2;
        }
        else
        {   buf[y]=url_enc[x];   }
    }
    buf[y]=ZERO;
    strcpy(url, buf);

    free(buf);
    return(url);
}/*}}}*/
